import { 
  saveJob, 
  findJobById, 
  findJobsByRecruiterId, 
  findAllJobs, 
  updateJob, 
  deleteJob 
} from './storageService';
import { generateId } from './storageService';

// 发布新职位
export function createJob(jobData, recruiterId) {
  // 验证必填字段
  if (!jobData.title || !jobData.description || !jobData.company || !jobData.location) {
    throw new Error('请填写所有必填字段');
  }

  // 创建职位对象
  const job = {
    id: generateId(),
    title: jobData.title,
    description: jobData.description,
    company: jobData.company,
    salary: jobData.salary || '',
    location: jobData.location,
    recruiterId: recruiterId,
    createdAt: new Date().toISOString()
  };

  // 保存职位到存储
  if (saveJob(job)) {
    return job;
  } else {
    throw new Error('职位发布失败，请重试');
  }
}

// 更新职位
export function updateJobInfo(jobId, jobData) {
  // 验证必填字段
  if (!jobData.title || !jobData.description || !jobData.company || !jobData.location) {
    throw new Error('请填写所有必填字段');
  }

  // 更新职位信息
  const updatedJob = {
    title: jobData.title,
    description: jobData.description,
    company: jobData.company,
    salary: jobData.salary || '',
    location: jobData.location,
    updatedAt: new Date().toISOString()
  };

  // 更新职位到存储
  if (updateJob(jobId, updatedJob)) {
    return findJobById(jobId);
  } else {
    throw new Error('职位更新失败，请重试');
  }
}

// 删除职位
export function removeJob(jobId) {
  // 删除职位
  if (deleteJob(jobId)) {
    return true;
  } else {
    throw new Error('职位删除失败，请重试');
  }
}

// 获取职位详情
export function getJobById(jobId) {
  return findJobById(jobId);
}

// 获取招聘方发布的所有职位
export function getJobsByRecruiter(recruiterId) {
  return findJobsByRecruiterId(recruiterId);
}

// 获取所有职位
export function getAllJobs() {
  return findAllJobs();
}

// 根据关键词搜索职位
export function searchJobs(keyword) {
  const jobs = findAllJobs();
  if (!keyword) return jobs;
  
  const lowerKeyword = keyword.toLowerCase();
  return jobs.filter(job => 
    job.title.toLowerCase().includes(lowerKeyword) ||
    job.company.toLowerCase().includes(lowerKeyword) ||
    job.description.toLowerCase().includes(lowerKeyword) ||
    job.location.toLowerCase().includes(lowerKeyword)
  );
}

// 根据条件筛选职位
export function filterJobs(filters) {
  let jobs = findAllJobs();
  
  // 按地点筛选
  if (filters.location) {
    jobs = jobs.filter(job => 
      job.location.toLowerCase().includes(filters.location.toLowerCase())
    );
  }
  
  // 按薪资范围筛选
  if (filters.salary) {
    jobs = jobs.filter(job => 
      job.salary && job.salary.includes(filters.salary)
    );
  }
  
  return jobs;
}